import guid from '@/libs/guid.js'
import { fabric } from 'fabric'
import Element from './Element.js'
import EventEmitter from './EventEmitter.class.js'
import Flow from './Flow.js'
import Panel from './Panel.js'
import { reactive } from 'vue'
const defaultConfig = {
  expand: 1
}
import Basic from './Basic.js'

export default class FlowGroup extends Basic {
  constructor(options) {
    const component = new fabric.Group()
    super({
      component
    })
    this.type = 'group'
    this.config = Object.assign(
      {
        name: '组' + this.guid.slice(0, 3),
        type: 0 //默认流式
      },
      defaultConfig
    )
    this.flowLayout = new Flow({
      list: this.list
    })

    this.on('move', () => {
      this.refresh()
    })
  }
  add(item, update = 1, unshift = 0, index = -1) {
    super.add(item)
    if (unshift) {
      super.moveTop(item)
    }
    this.resizeHeight()
    this.initResize(item)
    this.component.canvas && this.component.canvas.renderAll()
    //this.component.addWithUpdate(item.component)
  }
  toggle() {
    this.config.expand = !this.config.expand
  }
  initResize(item) {
    item.on('update', (res) => {
      this.resizeHeight()
    })
  }
  /**
   * 调整高度,自适应变化
   */
  resizeHeight() {
    if (this.config.type == 1) {
      this.component.addWithUpdate()
      this.flowLayout.build()
    }
    this.component.addWithUpdate()
    this.component.canvas && this.component.canvas.renderAll()
  }
  update() {
    this.resizeHeight()
  }
  del(elem) {
    super.del(elem)
    this.resizeHeight()
  }
  refresh() {
    this.resizeHeight()
  }
  static fromCanvas(options) {
    let { component, canvas } = options
    let childs = component.getObjects()

    let group = new FlowGroup({
      component
    })

    childs.forEach((res) => {
      let elem = new Element({
        component: res
      })
      group.add(elem)
    })

    let json = component.toJSON()
    json.objects = []
    group.config = component.config || defaultConfig
    group.component.set(json)
    return group
  }
}
